<template>
  <div>
    <div class="router-content">
      <div v-if="pageType == 'list'">
        <QueryBar
          :queryForm="queryForm"
          :queryConfig="queryBar"
          @handleQueryClick="handleQueryClick"
        />
        <div style="margin-bottom: 20px">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="addList"
            v-if="add"
            >新增角色</el-button
          >
        </div>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="50">
            <template slot-scope="scope">{{
              10 > scope.$index + 1
                ? "0" + (scope.$index + 1)
                : scope.$index + 1
            }}</template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <!-- <el-table-column prop="default" label="角色类型"> </el-table-column> -->
          <el-table-column prop="roleDescription" label="角色描述">
          </el-table-column>
          <el-table-column prop="disabled" label="状态">
            <template slot-scope="scope">
              {{ scope.row.disabled ? "禁用" : "启用" }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="创建时间">
          </el-table-column>
          <el-table-column prop="updateName" label="操作人"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div v-if="scope.row.defaulted">不可操作</div>
              <div v-else>
                <el-tag
                  v-if="edit"
                  style="cursor: pointer; margin-right: 10px"
                  @click="handleOptions({ key: '1', index: scope.$index })"
                  size="medium"
                  >修改</el-tag
                >
                <el-tag
                  v-if="!scope.row.disabled && disable"
                  style="cursor: pointer"
                  @click="handleOptions({ key: '2', index: scope.$index })"
                  size="medium"
                  >禁用</el-tag
                >
                <el-tag
                  v-if="scope.row.disabled && enable"
                  style="cursor: pointer"
                  @click="handleOptions({ key: '3', index: scope.$index })"
                  size="medium"
                  >启用</el-tag
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 50px"
          @current-change="handlePageChange"
          :current-page="pageParams.pageNum"
          :page-sizes="[pageParams.pageSize]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        ></el-pagination>
      </div>
      <div v-else>
        <div v-if="pageType == 'add' || pageType == 'edit'">
          <el-form
            :model="formModel"
            :rules="formRules"
            ref="formModel"
            label-width="130px"
          >
            <el-form-item
              label="角色名称"
              style="width: 450px;22px"
              prop="roleName"
            >
              <el-input
                v-model="formModel.roleName"
                placeholder="请输入角色名称"
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色描述" style="width: 450px">
              <el-input
                v-model="formModel.roleDescription"
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 7 }"
                maxlength="100"
                placeholder="请输入100字内角色描述"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色权限" prop="permissionId">
              <tree
                ref="ztree"
                :setting="setting"
                :nodes="roleMenus"
                @onCheck="onCheck"
                @onCreated="handleCreated"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('formModel')"
                :loading="$store.state.subLoading"
                >确认</el-button
              >
              <el-button @click="closeForm">关闭</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <Modal
        :title="
          modalType == 'enable'
            ? '启用提示'
            : modalType == 'disable'
            ? '禁用提示'
            : ''
        "
        :dialogVisible="visible"
        :loading="$store.state.subLoading"
        @handleClose="handleCancel"
        @handleConfirm="handleConfirm"
      >
        <div
          v-if="modalType == 'enable'"
          style="display: flex; align-items: center"
        >
          <i
            class="el-icon-warning"
            style="color: #faad14; font-size: 18px; margin: 0 20px"
          ></i>
          确定启用该角色吗？
        </div>
        <div
          v-else-if="modalType == 'disable'"
          style="display: flex; align-items: center"
        >
          <i
            class="el-icon-warning"
            style="color: #faad14; font-size: 18px; margin: 0 20px"
          ></i>
          确定禁用该角色吗？
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import QueryBar from "@/components/common/QueryBar.vue";
import TableComponent from "@/components/common/TableComponent.vue";
import Modal from "@/components/common/Modal.vue";
import { queryBar, tableColumns } from "./configuration/role";
import api from "@/api/modules/permissions/role.js";
import util from "@/utils";
import tree from "vue-giant-tree";
export default {
  name: "role",
  components: { QueryBar, TableComponent, Modal, tree },
  data() {
    return {
      add: true,
      edit: true,
      enable: true,
      disable: true, //按钮权限

      pageType: "list",
      modalType: "",
      visible: false,
      queryForm: {},
      queryBar: queryBar,
      currentRow: "",
      tableData: [],
      tableColumns: tableColumns,
      count: 0,
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      roleMenus: [],
      ztreeObj: null,
      setting: {
        check: {
          enable: true,
          // chkStyle: "checkbox",
          // chkboxType: { Y: "ps", N: "s" },
        },
        data: { key: { name: "permissionName" } },
        view: { showIcon: false },
      },
      formModel: {
        roleName: "",
        permissionId: [],
        roleDescription: "",
      },
      formRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "change" },
        ],
        permissionId: {
          required: true,
          type: "array",
          message: "请选择角色权限",
          trigger: "change",
        },
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      // 设置页面按钮权限
      let btns = this.$store.state.userInfo.list[0].children[0];
      this.add = btns.children[0].havePermission;
      this.edit = btns.children[1].havePermission;
      this.enable = btns.children[2].havePermission;
      this.disable = btns.children[3].havePermission;

      this.getData(this.pageParams);
      api.getPermissionList().then((res) => {
        this.roleMenus = res.data;
        this.formModel.permissionId = [];
      });
    });
  },
  methods: {
    onCheck(val) {
      let nodes = this.ztreeObj.getCheckedNodes();
      this.formModel.permissionId = nodes.map((item) => item.permissionId);
      this.$refs["formModel"].validateField("permissionId");
    },
    handleCreated: function (ztreeObj) {
      this.ztreeObj = ztreeObj;
      ztreeObj.expandNode(ztreeObj.getNodes()[0], true);
    },
    reloadTree(data) {
      let resNode = {
        permissionId: data.permissionId,
        permissionName: data.permissionName,
      };
      if (this.formModel.permissionId.includes(resNode.permissionId)) {
        resNode.checked = true;
      }
      if (data.children && data.children.length > 0) {
        resNode.children = data.children.map(this.reloadTree);
      }
      return resNode;
    },
    closeForm(formName) {
      // this.$refs[formName].resetFields();
      this.pageType = "list";
    },
    getData(params) {
      try {
        api.getRolePage(params ? params : { ...this.pageParams, ...this.queryForm }).then((res) => {
          this.tableData = res.data;
          this.count = +res.count;
          this.pageType = "list";
        });
      } catch (error) {}
    },
    addList() {
      Object.keys(this.formModel).forEach((item) => {
        this.formModel[item] = "";
      });
      this.formModel.permissionId = [];
      this.roleMenus = this.roleMenus.map(this.reloadTree);
      this.pageType = "add";
    },
    handleCancel() {
      this.visible = false;
    },
    handleConfirm() {
      this.$store.commit("setSubLoading", true);
      switch (this.modalType) {
        case "enable":
          api.enableRole({ roleId: this.currentRow.roleId }).then((res) => {
            this.$message.success("启用成功");
            this.visible = false;
            this.getData({ ...this.pageParams, ...this.queryForm });
          });
          break;
        case "disable":
          api.disableRole({ roleId: this.currentRow.roleId }).then((res) => {
            this.$message.success("禁用成功");
            this.visible = false;
            this.getData({ ...this.pageParams, ...this.queryForm });
          });

          break;
      }
    },
    handleOptions(val) {
      const { key, index } = val;
      this.currentRow = this.tableData[index];
      switch (key) {
        case "1":
          this.formModel.permissionId = [];
          // 递归反填用户权限
          let fn = (permissions) => {
            permissions.forEach((item) => {
              if (item.havePermission) {
                this.formModel.permissionId.push(item.permissionId);
              }
              if (item.children && item.children.length) {
                fn(item.children);
              } else {
                return;
              }
            });
            this.pageType = "edit";
          };
          api.getRole({ roleId: this.currentRow.roleId }).then((res) => {
            this.formModel.roleName = res.data.roleName;
            this.formModel.roleDescription = res.data.roleDescription;
            fn(res.data.list);
            this.roleMenus = this.roleMenus.map(this.reloadTree);
          });

          break;
        case "2":
          this.modalType = "disable";
          this.visible = true;
          break;
        case "3":
          this.modalType = "enable";
          this.visible = true;
          break;
      }
    },
    handlePageChange(val) {
      this.pageParams.pageNum = val;
      this.getData({ ...this.pageParams, ...this.queryForm });
    },
    handleQueryClick(val) {
      switch (val) {
        case "search":
          if (this.queryForm.timeRange) {
            let obj = {
              roleName: this.queryForm.roleName,
              startTime: util.formatTime(this.queryForm.timeRange[0]),
              endTime: util.formatTime(this.queryForm.timeRange[1]),
            };
            this.pageParams.pageNum = 1;
            this.getData({ ...this.pageParams, ...obj });
          } else {
            this.pageParams.pageNum = 1;
            this.getData({ ...this.pageParams, ...this.queryForm });
          }

          break;
        case "reset":
          Object.keys(this.queryForm).forEach((item) => {
            this.queryForm[item] = "";
          });
          this.pageNum = 1;
          this.getData(this.pageParams);
          break;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // if (!this.formModel.permissionId.includes(1)) {
          //   this.$message.warning("请添加首页权限");
          //   return;
          // }
          this.$store.commit("setSubLoading", true);
          if (this.pageType == "add") {
            api.addRole(this.formModel).then((res) => {
              this.$message.success("新增成功");
              this.pageParams.pageNum=1
              this.getData();
            });
          } else {
            api
              .modifyRole({
                ...this.formModel,
                ...{ roleId: this.currentRow.roleId },
              })
              .then((res) => {
                this.$message.success("编辑成功");
                this.getData();
              });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.details-page {
  h5 {
    font-size: 16px;
  }
  ul {
    width: 100%;
    li {
      float: left;
      margin-bottom: 15px;
      width: 33.3% !important;
      span {
        color: #666;
      }
    }
  }

  .basic {
    height: 150px;
    border-bottom: 1px solid #ccc;
  }
  .option {
    margin-top: 50px;
    text-align: center;
  }
  .modalContent {
    display: flex;
    align-items: center;
    .el-icon-question {
      font-size: 20px;
      margin-right: 20px;
      color: #faad14;
    }
  }
  .portal {
    > div {
      min-height: 330px;
    }
  }
}
</style>
